#ifndef GAMESERVER_H
#define GAMESERVER_H

#include <QThread>
#include <QHostAddress>
#include <QTcpServer>
#include <QTcpSocket>
#include <QSignalMapper>
#include <QList>
#include <set>

#include "card.h"
#include "message.h"
#include "gamestate.h"

class GameServer : public QObject // QThread
{
    Q_OBJECT
public:
    GameServer();
    ~GameServer();

    static constexpr int maximumPlayers = 3;

    bool start(quint16 port, QThread* thread);

private slots:
    void newClientConnection();
    void broadcast(MessageType type, qint32 data = 0);
    void broadcast(MessageType type, const QString& str);

private:
    void action(QTcpSocket* socket, Message& m, const QByteArray& s);
    void onReadyRead(QTcpSocket* socket);
    void onClientDisconnected(QTcpSocket* socket);
    QByteArray makeMessage(int player) const;
    void generateCards();
    void distributeCards();
    int determineLandlord();
    void resetState();

    QTcpServer *tcpServer;
    std::set<QTcpSocket*> sockets; // all sockets, which can be more than the number of players
    QTcpSocket* players[maximumPlayers];
    int preempted[maximumPlayers], cardsPosted[maximumPlayers];
    // -1: not determined, 0: not preempted, positive: preempted
    GameState state;
    int numPlayers, currentPlayer, landlord, lastPostedPlayer;
    bool exiting;

    QList<Card> cards[maximumPlayers];
    QList<Card> remainingCards;
    QByteArray postedCardsRepr; // postedCards: previously posted
};

#endif // GAMESERVER_H
